const rp = require('request-promise');
const setToken = require('../utils/setToken');
const miniProgramConfig = require('../config/miniConfig.json');
const UserModel = require('../models/user');

class UserController {
  static async login(ctx) {
    const { code } = ctx.query;
    const req = await rp({
      url: `https://api.weixin.qq.com/sns/jscode2session?appid=${miniProgramConfig.appi}&secret=${miniProgramConfig.secret}&js_code=${code}&grant_type=authorization_code`,
      method: 'get',
    });

    const { openid } = JSON.parse(req);
    if (openid !== undefined) {
      const list = await UserModel.findOrCreate(openid);
      ctx.body = {
        token: setToken.setToken(list[0].id),
        userInfo: list[0],
      };
    } else {
      ctx.throw(404, '404,openid error');
      // throw new Error('404,openid error', 404);
    }
  }
}
module.exports = UserController;
